<script setup>
defineProps({
  defaultPlaceholder: {
    type: String,
    default: '写下你的评论...',
  },
})
const commentText = ref('')
const emojis = ref([
  '😀',
  '😃',
  '😄',
  '😁',
  '😆',
  '😅',
  '😂',
  '🤣',
  '😊',
  '😇',
  '🙂',
  '🙃',
  '😉',
  '😌',
  '😍',
  '🥰',
  '😘',
  '😗',
  '😙',
  '😚',
  '😋',
  '😛',
  '😝',
  '😜',
  '🤪',
  '🤨',
  '🧐',
  '🤓',
  '😎',
  '🤩',
  '🥳',
  '😏',
  '😒',
  '😞',
  '😔',
  '😟',
  '😕',
  '🙁',
  '☹️',
  '😣',
  '😖',
  '😫',
  '😩',
  '🥺',
  '😢',
  '😭',
  '😤',
  '😠',
  '😡',
  '🤬',
  '🤯',
  '😳',
  '🥵',
  '🥶',
  '😱',
  '😨',
  '😰',
  '😥',
  '😓',
  '🤗',
  '🤔',
  '🤭',
  '🤫',
  '🤥',
  '😶',
  '😐',
  '😑',
  '😬',
  '🙄',
  '😯',
  '😦',
  '😧',
  '😮',
  '😲',
  '🥱',
  '😴',
  '🤤',
  '😪',
  '😵',
  '🤐',
  '🥴',
  '🤢',
  '🤮',
  '🤧',
  '😷',
  '🤒',
  '🤕',
  '🤑',
  '🤠',
  '😈',
  '👿',
  '👹',
  '👺',
  '🤡',
  '💩',
  '👻',
  '💀',
  '☠️',
  '👽',
  '👾',
  '🤖',
  '🎃',
  '😺',
  '😸',
  '😹',
  '😻',
  '😼',
  '😽',
  '🙀',
  '😿',
  '😾',
])
const textareaRef = ref(null)
const picList = ref([
  'https://picsum.photos/id/237/200/200',
  'https://picsum.photos/id/227/200/100',
])

const maxLength = 1000 // 最大字数限制

watch(commentText, (newVal) => {
  if (newVal.length > maxLength) {
    commentText.value = newVal.slice(0, maxLength)
  }
})

function keepFocus() {
  textareaRef.value?.focus()
}

// 插入表情符号
async function insertEmoji(emoji) {
  const textarea = textareaRef.value?.textarea
  if (!textarea)
    return

  // 保存当前光标位置和选区状态
  const startPos = textarea.selectionStart
  const endPos = textarea.selectionEnd

  // 插入表情符号
  commentText.value
    = commentText.value.substring(0, startPos)
      + emoji
      + commentText.value.substring(endPos)

  // 等待DOM更新
  await nextTick()

  // 计算新的光标位置
  const newCursorPos = startPos + emoji.length

  // 恢复光标位置
  textarea.selectionStart = newCursorPos
  textarea.selectionEnd = newCursorPos

  // 保持焦点
  textarea.focus()
}

// 提交评论
async function handleSubmit() {
  if (commentText.value.trim()) {
    console.log('提交评论:', commentText.value)
    // 这里可以添加提交逻辑
    commentText.value = ''
  }
}

// el-upload 配置
const uploadProps = {
  action: '#',
  multiple: false, // 允许上传多个文件
  accept: 'image/*', // 限制为图片类型
  showFileList: false, // 不显示默认的文件列表
  limit: 5,
  onSuccess: (response, file) => {
    console.log('上传成功:', response, file)
    // 假设接口返回图片URL
    const imageUrl = 'https://picsum.photos/id/237/200/200'
    picList.value.push(imageUrl) // 将新图片添加到 picList
  },
  onError: (error) => {
    console.error('上传失败:', error)
    $message.error('上传失败，请重试')
  },
}

// 移除图片
function removeImage(index) {
  picList.value.splice(index, 1)
}

const isTextareaFocused = ref(false)
</script>

<template>
  <div
    class="comment-container"
    :class="{ 'focused-border': isTextareaFocused }"
  >
    <!-- 文本输入区域 -->
    <el-input
      ref="textareaRef"
      v-model="commentText"
      type="textarea"
      :rows="3"
      :autosize="{ minRows: 3, maxRows: 8 }"
      :placeholder="defaultPlaceholder"
      resize="none"
      class="comment-textarea"
      @keydown.enter.exact.prevent="handleSubmit"
      @focus="isTextareaFocused = true"
      @blur="isTextareaFocused = false"
    />

    <!-- 工具栏 -->
    <div class="flex-col p-10" @mousedown.prevent.stop="keepFocus">
      <div class="mb-5 w-full flex flex-1 items-center justify-start">
        <div v-for="(url, index) in picList" :key="index" class="relative mr-5">
          <el-image
            :src="url"
            lazy
            :preview-src-list="picList"
            :initial-index="index"
            fit="cover"
            class="size-60 border-rd-5"
          />
          <!-- 移除图标 -->
          <div
            class="absolute right-2 top-2 flex border-rd-50"
            @click.stop="removeImage(index)"
          >
            <i class="i-ep:close-bold cursor-pointer-text-hover" />
            <!-- 使用 Element Plus 的关闭图标 -->
          </div>
        </div>
      </div>
      <div class="w-full flex flex-1 items-center justify-between">
        <!-- 左侧表情包按钮 -->
        <div class="f-c-c">
          <el-popover placement="top-start" trigger="click" :width="400">
            <template #reference>
              <span
                class="emoji-btn cursor-pointer font-size-24 us"
                @mousedown.prevent.stop
              >
                😊
              </span>
            </template>
            <!-- 表情包选择器 -->
            <div class="emoji-picker" @mousedown.prevent.stop>
              <div
                v-for="emoji in emojis"
                :key="emoji"
                class="emoji-item"
                @click="insertEmoji(emoji)"
                @mousedown.prevent
              >
                {{ emoji }}
              </div>
            </div>
          </el-popover>
          <el-upload v-bind="uploadProps" class="ml-10 f-c-c">
            <template #trigger>
              <i class="i-bi:image font-size-24" />
            </template>
          </el-upload>
        </div>

        <!-- 右侧发送按钮 -->
        <div class="flex items-center">
          <span class="mr-10 font-size-14 op-text us">{{ commentText.trim().length }}/{{ maxLength }}</span>
          <el-button
            type="primary"
            :disabled="!commentText.trim()"
            class="send-btn"
            @click="handleSubmit"
            @mousedown.prevent.stop
          >
            发送
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.focused-border {
  box-shadow: 0 0 0 1px var(--el-color-primary);
}

.comment-container {
  background-color: var(--el-bg-color-page);
  border-radius: 5px;
}

.comment-textarea :deep(.el-textarea__inner) {
  font-size: 14px;
  line-height: 1.5;
  border: none;
  box-shadow: none;
  background-color: transparent;
}

.comment-textarea :deep(.el-textarea__inner:focus) {
  box-shadow: none;
}

.emoji-picker {
  display: grid;
  grid-template-columns: repeat(8, 1fr);
  gap: 8px;
  max-height: 300px;
  overflow-y: auto;
}

.emoji-item {
  font-size: 20px;
  cursor: pointer;
  text-align: center;
  border-radius: 5px;
}

.emoji-item:hover {
  background-color: #f0f0f0;
}

.send-btn {
  width: 80px;
}

.emoji-btn {
  display: inline-block;
}
</style>
